$(function () {
    //1.点击a链接，切换盒子
    $("#loginBox a").on("click", function () {
        $("#loginBox").hide();
        $("#registerBox").show();
    });
    $("#registerBox a").on("click", function () {
        $("#registerBox").hide();
        $("#loginBox").show();
    });
    //2.自定义校验规则
    let form = layui.form;
    form.verify({
        pwd: [
            /^[\S]{6,15}$/, 
            "密码的长度为6-15个字符，且不能包含空格",
        ],
        repwd: function (value) {
            let oldPwd = $("#registerBox [name=password]").val();
            if (value !== oldPwd) {
                return "两次输入密码不一致";
            }
        },
    });
    //3.注册axios
    let layer = layui.layer;
    $("#form-reg").on("submit", function (e) {
        e.preventDefault();
        axios({
            method: "POST",
            url: "/api/reguser",
            data: $("#form-reg").serialize(),
        }).then((res) => {
            if (res.data.status !== 0) return layer.msg(res.data.message)
            layer.msg('恭喜您，注册成功');
            $("#form-reg")[0].reset();
            $("#registerBox a").triggerHandler('click')
        });
    });
    //4.登录axios
    $("#form-login").on("submit", function (e) {
        e.preventDefault();
        axios({
            method: "POST",
            url: "/api/login",
            data: $("#form-login").serialize(),
        }).then((res) => {
            if (res.data.status !== 0) return layer.msg(res.data.message)
            layer.msg('恭喜您，登录成功');
            location.href = '/index.html';
            localStorage.setItem('token', res.data.token);
        });
    });
});